package org.example;

import javax.servlet.AsyncContext;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/asyncUser", asyncSupported = true)
public class AsyncUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("asyncUser");
        // 1.获取异步上下文
        AsyncContext asyncContext = req.startAsync();
        asyncContext.start(() -> {
            try {
                System.out.println("进入异步线程");
                // 2.处理业务逻辑

                Thread.sleep(5000);

                // 3.获取响应
                ServletResponse response = asyncContext.getResponse();
                response.getWriter().write("success");

                // 4.完成
                asyncContext.complete();



            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }

        });

    }
}
